package com.jbwz.web.security.config.security;

import com.jbwz.web.common.session.SecurityUserHolder;
import com.jbwz.web.common.session.SessionUser;
import com.jbwz.web.security.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.function.Supplier;

@Slf4j
@Component
public class AccessDecisionManger implements AuthorizationManager<RequestAuthorizationContext> {
  @Autowired private UserService userService;

  public boolean checkPermission(Authentication authentication, HttpServletRequest request) {
    String path = request.getServletPath();
    SessionUser currentUser = SecurityUserHolder.getCurrentUser();
    RequestMatcher requestMatcher = currentUser.getRequestMatcher();
    if (Objects.isNull(requestMatcher)) {
      return false;
    }
    boolean b = requestMatcher.matches(request);
    log.info("校验用户:{}权限Path:{}权限：{}", currentUser.getUsername(), path, b);
    return b;
  }

  @Override
  public AuthorizationDecision check(
      Supplier<Authentication> authentication, RequestAuthorizationContext object) {
    boolean b = checkPermission(authentication.get(), object.getRequest());
    return new AuthorizationDecision(b);
  }
}
